var express = require("express");
var router = express.Router();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const uuid = require("uuid");

//获取评论数
router.get("/num", async (req, res) => {
  const { topic_id, topic_type } = req.query;

  const comment_list = await prisma.user_comment.findMany({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
    },
  });

  res.json(comment_list.length);
});

//获取评论列表和评论数
router.get("", async (req, res) => {
  const { topic_id, topic_type } = req.query;

  //评论列表
  const comment_list = await prisma.user_comment.findMany({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
    },
    orderBy: {
      time: "desc",
    },
    include: {
      user_all: {
        select: {
          avatar: true,
        },
      },
    },
  });
  comment_list.forEach((item) => {
    item.reply_show = false;
    if(item.user_all.avatar == null) item.user_all.avatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
  });
  //一级评论列表
  let comment_first_list = comment_list.filter((item) => {
    return item.type == 0;
  });
  //二级评论列表
  let comment_second_list = comment_list.filter((item) => {
    return item.type == 1;
  });
  //二级评论列表-根据一级评论分组
  let comment_second_group = comment_second_list.reduce((result, item) => {
    const key = item.first_comment_id.toString();
    result[key] = [...(result[key] || []), item];
    return result;
  }, {});
  //将二级评论列表放到一级评论的children字段中
  for (let key in comment_second_group) {
    const index = comment_first_list.findIndex((item) => {
      return item.comment_id == key;
    });
    if (index != -1) {
      comment_first_list[index].children = [...comment_second_group[key]];
    }
  }

  //返回值
  let result = {};
  result.total = comment_list.length;
  result.list = comment_first_list;
  res.json(result);
});

//新增评论
router.post("", async (req, res) => {
  const { topic_id, topic_type, content, time, type } = req.body;
  let new_data = { topic_id: topic_id, topic_type: parseInt(topic_type), content: content, type: parseInt(type) };
  new_data.comment_id = uuid.v4();
  new_data.time = new Date().getTime().toString();
  new_data.from_user_id = req.auth.user.user_id;
  new_data.from_user_name = req.auth.user.user_name;
  if (parseInt(type) == 1) {
    //二级评论
    new_data.first_comment_id = req.body.first_comment_id;
    new_data.to_comment_id = req.body.to_comment_id;
    new_data.to_user_id = parseInt(req.body.to_user_id);
    new_data.to_user_name = req.body.to_user_name;
  }

  //新增
  const new_comment = await prisma.user_comment.create({
    data: new_data,
  });

  res.json(new_comment);
});

//删除评论
router.delete("", async (req, res) => {
  const { comment_id } = req.query;

  //级联删除
  const comment_delete = await prisma.user_comment.delete({
    where: {
      comment_id: comment_id,
    },
  });
  res.json(comment_delete);
});

module.exports = router;
